package com.example.backend.service;

import com.example.backend.domain.entity.Comment;
import com.example.backend.domain.entity.Ticket;
import com.example.backend.domain.entity.User;
import com.example.backend.domain.enums.CommentType;
import com.example.backend.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class CommentService {

    @Autowired
    private CommentRepository commentRepository;

    /**
     * 创建评论
     */
    public Comment createComment(Ticket ticket, User author, String content, 
                               CommentType commentType, Boolean isInternal, Comment parent) {
        Comment comment = Comment.builder()
                .ticket(ticket)
                .author(author)
                .content(content)
                .commentType(commentType)
                .isInternal(isInternal != null ? isInternal : false)
                .parent(parent)
                .build();
        
        return commentRepository.save(comment);
    }

    /**
     * 更新评论
     */
    public Comment updateComment(Long commentId, String content, String editReason) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("评论不存在"));
        
        comment.setContent(content);
        comment.setIsEdited(true);
        comment.setEditedAt(Instant.now());
        comment.setEditReason(editReason);
        
        return commentRepository.save(comment);
    }

    /**
     * 删除评论
     */
    public void deleteComment(Long commentId) {
        commentRepository.deleteById(commentId);
    }

    /**
     * 获取工单的所有评论
     */
    @Transactional(readOnly = true)
    public List<Comment> getTicketComments(Long ticketId) {
        return commentRepository.findByTicketIdOrderByCreatedAtAsc(ticketId);
    }

    /**
     * 分页获取工单评论
     */
    @Transactional(readOnly = true)
    public Page<Comment> getTicketComments(Long ticketId, Pageable pageable) {
        return commentRepository.findByTicketIdOrderByCreatedAtDesc(ticketId, pageable);
    }

    /**
     * 获取工单的公开评论
     */
    @Transactional(readOnly = true)
    public List<Comment> getPublicTicketComments(Long ticketId) {
        return commentRepository.findByTicketIdAndIsInternalFalseOrderByCreatedAtAsc(ticketId);
    }

    /**
     * 获取工单的内部评论
     */
    @Transactional(readOnly = true)
    public List<Comment> getInternalTicketComments(Long ticketId) {
        return commentRepository.findByTicketIdAndIsInternalTrueOrderByCreatedAtAsc(ticketId);
    }

    /**
     * 获取顶级评论（非回复）
     */
    @Transactional(readOnly = true)
    public List<Comment> getTopLevelComments(Long ticketId) {
        return commentRepository.findTopLevelCommentsByTicketId(ticketId);
    }

    /**
     * 获取评论的回复
     */
    @Transactional(readOnly = true)
    public List<Comment> getCommentReplies(Long parentId) {
        return commentRepository.findByParentIdOrderByCreatedAtAsc(parentId);
    }

    /**
     * 获取用户的评论
     */
    @Transactional(readOnly = true)
    public Page<Comment> getUserComments(Long authorId, Pageable pageable) {
        return commentRepository.findByAuthorId(authorId, pageable);
    }

    /**
     * 统计工单评论数量
     */
    @Transactional(readOnly = true)
    public Long countTicketComments(Long ticketId) {
        return commentRepository.countByTicketId(ticketId);
    }

    /**
     * 统计工单内部/公开评论数量
     */
    @Transactional(readOnly = true)
    public Long countTicketCommentsByType(Long ticketId, Boolean isInternal) {
        return commentRepository.countByTicketIdAndIsInternal(ticketId, isInternal);
    }

    /**
     * 点赞评论
     */
    public Comment likeComment(Long commentId) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("评论不存在"));
        
        comment.setLikeCount(comment.getLikeCount() + 1);
        return commentRepository.save(comment);
    }

    /**
     * 点踩评论
     */
    public Comment dislikeComment(Long commentId) {
        Comment comment = commentRepository.findById(commentId)
                .orElseThrow(() -> new RuntimeException("评论不存在"));
        
        comment.setDislikeCount(comment.getDislikeCount() + 1);
        return commentRepository.save(comment);
    }

    /**
     * 获取评论详情
     */
    @Transactional(readOnly = true)
    public Optional<Comment> getCommentById(Long commentId) {
        return commentRepository.findById(commentId);
    }
}